package com.stsmobile;

import com.stsmobile.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class Welcome extends Activity{
	private static final CharSequence ERROR_CONNECTION = "Unable to connect\n" +
														"to the STS database.";
	protected static final String NON_NUMBER_INPUT = "The user input value was not a number. Please retry.";
	private static final CharSequence ERROR_NOT_LOGGED_IN = "User is not logged in.";
	private Button search, enter, scan;

	@Override
	public void onResume(){
		super.onResume();
		if(STSApplication.loggingOut()){
			finish();
		}
		STSApplication.toHome(false);
	}
	
	@Override
	public void onCreate(Bundle a){
		super.onCreate(a);
		setContentView(R.layout.welcome);
		final Context con = this;
		
		TextView txt = (TextView) findViewById(R.id.usernameLabel);
        txt.setText(STSApplication.getUsername());
		
        
		search = (Button) findViewById(R.id.bsearch);
		search.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				//Display Error Message to User in a Popup
				String institution_id= STSApplication.getInstitutionId();
				String result = STSApplication.search(institution_id);
				if(result.contains("<error>")){
					makeXmlMessageToast(result,Toast.LENGTH_LONG);
				}
				else if (result.contains("<success")){
					Intent searchlist = new Intent("com.stsmobile.Search");
					startActivity(searchlist);
				}
			}
		});
		
		enter = (Button) findViewById(R.id.benter);
		enter.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				makeSearchPopup(con);
			}
		});
		
		scan = (Button) findViewById(R.id.bscan);
		scan.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent scanner = new Intent("com.google.zxing.client.android.SCAN");
				scanner.putExtra("SCAN_MODE", "QR_CODE_MODE");
		        startActivityForResult(scanner, 0);
			};
		});
		
	}
	public void onActivityResult(int requestCode, int resultCode, Intent scanner){
		if (requestCode == 0){
			if(resultCode==RESULT_OK){
				String contents = scanner.getStringExtra("SCAN_RESULT");
				//Pass the string to the search function
//				scannedresult = Integer.parseInt(contents);
				findShipment(contents);
			}
			else if(resultCode==RESULT_CANCELED){
				//Handle error in reading the code, display a "cannot read" alert
			}
		}
	}
	private void findShipment(String shipment_id) {
		String result = STSApplication.retrieveShipment(shipment_id);

		if(result.contains("<success>"))
		{
			Intent nextpage = new Intent("com.stsmobile.ShipmentHome");
			startActivity(nextpage);
		}else
		{
			makeXmlMessageToast(result,Toast.LENGTH_LONG);
		}
	}
	
	/**
	 * A popup that allows users to search by id.
	 * @param groupPosition
	 * @param childPosition
	 */
	private void makeSearchPopup(Context context)
	{
		//Defines the look of the popup
		AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
		final EditText integerBox = new EditText(context);
		integerBox.setHint("Enter Shipment's ID#");
		dialogBuilder.setTitle("Search by Shipment ID");
		dialogBuilder.setMessage("Find a shipment by typing it's ID number below:");
		dialogBuilder.setView(integerBox);
		
		//Defines the behavior of the popup
		dialogBuilder.setPositiveButton("Search", new DialogInterface.OnClickListener() 
		{
			@Override
			public void onClick(DialogInterface dialog, int which) {
				try
				{
					//convert newValue to an integer to check integrity
					Editable newValueEditable = integerBox.getEditableText();
//					int id = Integer.parseInt(newValueEditable.toString());
					findShipment(newValueEditable.toString());
					
					
				}catch (NumberFormatException e)
				{
					//error parsing, user input something that was not an integer.
					makeXmlMessageToast("<msg>"+NON_NUMBER_INPUT+"</msg>",
														Toast.LENGTH_LONG);
				}
			}
		});
		dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() 
		{
			@Override
			public void onClick(DialogInterface dialog, int which) {
				//Just exit the dialog with no changes
			}
		});
		AlertDialog alertdiagle = dialogBuilder.create();
		alertdiagle.show();
	}
	

	private void makeXmlMessageToast(String result, int duration){
		CharSequence message="";
		
		//Get error message from server's response.
		int startMessage = result.indexOf("<msg>")+5;
		int endMessage = result.indexOf("</msg>");
		
		if(startMessage!=-1 && endMessage!=-1)
			message = result.substring(startMessage,endMessage);
			
		if(message.equals(""))
			message=ERROR_CONNECTION;
		
		if(message.equals("Sitekey Authentication Failed"))
			message=ERROR_NOT_LOGGED_IN;
		
		//Display Message to User in a Popup
		Context cur_context = getApplicationContext();
		Toast displaymessage = Toast.makeText(cur_context, message, duration);
		displaymessage.show();
	}
	
	private static final int MENU_LOGOUT = Menu.FIRST;
	
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0,MENU_LOGOUT,0,"Logout");
		return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item){
		switch(item.getItemId()){
		case MENU_LOGOUT:
			logout();
			return true;
		}
		return false;
	}
	
	public void logout(){
		String result = STSApplication.logout();
		makeXmlMessageToast(result, Toast.LENGTH_LONG);
		STSApplication.loggingOut(true);
		finish();
	}
	
}
